<?php

namespace App\Models;

// use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OperationLog extends Model
{
    // use HasFactory;

    /**
     * 可批量赋值的属性
     */
    protected $fillable = [
        'user_id',
        'action',
        'target_type',
        'target_id',
        'content',
        'ip',
    ];

    /**
     * 获取关联的用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取操作类型文本
     */
    public function getActionTextAttribute()
    {
        $actions = [
            'login' => '登录',
            'logout' => '登出',
            'create' => '创建',
            'update' => '更新',
            'delete' => '删除',
            'inventory_in' => '入库',
            'inventory_out' => '出库'
        ];

        return $actions[$this->action] ?? $this->action;
    }

    /**
     * 获取目标类型文本
     */
    public function getTargetTypeTextAttribute()
    {
        $types = [
            'user' => '用户',
            'material' => '材料',
            'type' => '类型',
            'inventory' => '库存'
        ];

        return $types[$this->target_type] ?? $this->target_type;
    }

    /**
     * 记录操作日志
     */
    public static function log($userId, $action, $targetType = null, $targetId = null, $content = null)
    {
        return self::create([
            'user_id' => $userId,
            'action' => $action,
            'target_type' => $targetType,
            'target_id' => $targetId,
            'content' => $content,
            'ip' => request()->ip(),
        ]);
    }
} 